package com.easy.frame.base.api.pojo;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.easy.frame.base.basic.NameTag;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.ArrayList;
import java.util.List;

/**
 * 分页接口返回对象
 *
 * @author zzf
 * @date 2020/7/3 8:42
 */
@Getter
@Setter
@ToString
public class PageVO<T> implements NameTag {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty("当前页")
    private Integer current;

    @ApiModelProperty("每页大小")
    private Integer size;

    @ApiModelProperty("总数据量")
    private Long total;

    @ApiModelProperty("总页数")
    private Long pages;

    @ApiModelProperty("排序字段名")
    private String sortName;

    @ApiModelProperty(value = "排序方式 desc-倒序(默认) asc-正序")
    private String sortOrder;

    @ApiModelProperty("数据集合")
    private List<T> records;

    public List<OrderItem> orders() {
        List<OrderItem> orderItemList = new ArrayList<>(1);
        if (this.sortName != null) {
            orderItemList.add("asc".equalsIgnoreCase(sortOrder) ? OrderItem.asc(sortName) : OrderItem.desc(sortName));
        } else {
            orderItemList.add(OrderItem.desc("id"));
        }
        return orderItemList;
    }

    public void setTotal(long total) {
        this.total = total;
        this.pages = total / size + ((total % size) == 0 ? 0 : 1);
    }

    public int offset() {
        return getCurrent() > 0 ? (getCurrent() - 1) * getSize() : 0;
    }

    public PageVO(PageDTO<?> pageDTO) {
        this.current = pageDTO.getPageNum();
        this.size = pageDTO.getPageSize();
        this.sortName = pageDTO.getSortName();
        this.sortOrder = pageDTO.getSortOrder();
    }

}
